package
{
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	public class SpinLock
	{
		public var pollTimer:Timer;
		//private static var pollTimer:Timer;		
		private var tocall:Function;
		//private static var lock:Boolean = false;
		public var lock:Boolean = false;
		
		//private var trigger:EventDispatcher;				
		
		public function SpinLock()
		{
			//trigger = new EventDispatcher();
			//trigger.addEventListener(
			
			pollTimer = new Timer(1000, 0);
			pollTimer.addEventListener(TimerEvent.TIMER, poll);
			//debug("SpinLock Created.");
		}
		
		public function block(interval:int, fcall:Function):void {
			//debug("Wait Engaged.");
			pollTimer.delay = interval;
			tocall = fcall;
			lock = true;
			pollTimer.start();
			//debug("Timer Started.");			
		}
		
		private function poll(ev:TimerEvent):void {
			//debug("Polling...");
			if (lock == false) {				
				tocall.call();
				//debug("Wait Triggered.");
				pollTimer.stop();
			}
		}
		
		public function release():void {
			lock = false;
			//debug("Wait Disengaged.");
		}
		
		public function fire():void {
			//trigger.dispatchEvent(new TimerEvent());
			lock = false;
			pollTimer.dispatchEvent(new TimerEvent(TimerEvent.TIMER));
		}
		
//        private static function debug(msg:String):void {
//        	m1.debug.print("Synch: " + msg);
//        }
	}
}